#!/usr/bin/env node

var optimist = require('optimist'),
    fs = require('fs'),
    sys = require('sys'),
    concat = require('concat-stream'),
    csv2geojson = require('./'),
    argv = optimist
        .usage('Usage: $0 -lat [string] -lon [string] -delimeter [string] FILE')
        .describe('lat', 'the name of the latitude column')
        .describe('lon', 'the name of the longitude column')
        .describe('line', 'whether or not to output points as a LineString')
        .describe('delimiter', 'the type of delimiter')
        .default('delimiter', ',')
        .default('line', false)
        .argv;

if (process.stdin.isTTY && !argv._[0]) {
    return optimist.showHelp();
}
(argv._.length ? fs.createReadStream(argv._[0]) : process.stdin).pipe(concat(convert));

function convert(data) {
    csv2geojson.csv2geojson(data.toString(), {
        latfield: argv.lat,
        lonfield: argv.lon,
        delimiter: argv.delimiter
    }, function(err, data) {
        if (err) console.error(JSON.stringify(err, null, 2));
        if (argv.line) data = csv2geojson.toLine(data)
        console.log(JSON.stringify(data, null, 2));
    });
}
